<?php

namespace App\Models;

use App\Http\Controllers\PaymentController;
use App\Http\Controllers\QrCodeController;
use App\Http\Controllers\WxPayController;
use App\User;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

class LeaseGoods extends Model
{
    /***
     * @var string
     * 押金宝商品
     */
    protected $table = "c_lease_goods";

    //增加修改商品
    public function add($data)
    {
        try {
            DB::beginTransaction(); // 开始事务
//                更新
            if (isset($data['id']) && !empty($data['id'])) {
                $redata = self::getInfo($data['id']);
                $redata->goods_name = isset($data['goods_name']) ? $data['goods_name'] : $redata->goods_name;
                $redata->hospital_name = isset($data['hospital_name']) ? $data['hospital_name'] : $redata->hospital_name;
                $redata->goods_image = isset($data['goods_image']) ? $data['goods_image'] : $redata->goods_image;
                $redata->deposit_price = isset($data['deposit_price']) ? $data['deposit_price'] : $redata->deposit_price;
                $redata->stock_num = isset($data['stock_num']) ? $data['stock_num'] : $redata->stock_num;
                $redata->states = isset($data['states']) ? $data['states'] : $redata->states;
                $redata->deposit_describe = isset($data['deposit_describe']) ? $data['deposit_describe'] : $redata->deposit_describe;
                $redata->doctor_id = isset($data['doctor_id']) ? $data['doctor_id'] : $redata->doctor_id;
                $redata->work_id = isset($data['work_id']) ? $data['work_id'] : $redata->work_id;
                $res = $redata->save();
            } else { //添加
                $this->goods_name = isset($data['goods_name']) ? $data['goods_name'] : "";
                $this->hospital_name = isset($data['hospital_name']) ? $data['hospital_name'] : "";
                $this->goods_image = isset($data['goods_image']) ? $data['goods_image'] : "";
                $this->deposit_price = isset($data['deposit_price']) ? $data['deposit_price'] : "";
                $this->stock_num = isset($data['stock_num']) ? $data['stock_num'] : 0;
                $this->states = isset($data['states']) ? $data['states'] : 1;
                $this->deposit_describe = isset($data['deposit_describe']) ? $data['deposit_describe'] : "";
                $this->doctor_id = isset($data['doctor_id']) ? $data['doctor_id'] : 0;
                $this->work_id = isset($data['work_id']) ? $data['work_id'] : 0;
                $res = $this->save();
            }
            if ($res) {
                DB::commit(); // 提交事务
                return ['goods_id' => $this->id ?: $data['id']];
            } else {
                return '入驻失败';
                DB::rollback(); // 回滚事务
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }

    /**
     * @param $id
     * 获取商品详情
     */
    public static function getInfo($id)
    {
        return self::where(["id" => $id])->first();
    }

    /**
     * @param $id
     * @return int
     * 删除
     */
    public static function del($id)
    {
        return self::destroy($id);
    }

    /**
     * @param $id
     * 获取详情
     */
    public static function detail($id)
    {
        $result = self::getInfo($id);
        if (empty($result)) {
            return "暂无该商品!";
        }
        if (isset($result->goods_image)) {
            $result->host_goods_image = Url::getHttpHost() . 'upload/' . $result->goods_image;
        }
        return $result->toArray();
    }


    /**
     * 获取商品列表
     */
    public static function getList($filter)
    {
        $where = [];
        if (isset($filter['goods_name'])) {
            $where[] = ['goods_name', 'like', '%' . $filter['goods_name'] . '%'];
        }
        if (isset($filter['work_id'])) {
            $where[] = ['work_id', '=', $filter['work_id']];
        }
        if (isset($filter['states'])) {
            $where[] = ['states', '=', $filter['states']];
        }
        $list = self::where($where)->orderByDesc("id")->paginate(15)->toArray();
        if (!empty($list)) {
            $host = Url::getHttpHost();
            foreach ($list['data'] as $k => &$v) {
                $v['goods_image'] = $host . 'upload/' . $v['goods_image'];
            }
        }
        return $list;
    }

    /**
     * 获取订单二维码
     */
    public static function makeOrderQrCode($filter)
    {
        $order = Order::where(['id' => $filter['order_id']])->first();
        $order_id = Crypt::encrypt($filter['order_id']);
        $path = 'image/' . $order->work_id . '/';
        if (!is_dir($path)) {
            mkdir($path);
            chmod($path, 0777);
        }
        $file = 'image/' . $order->work_id . '/' . $order->sn . '_order.png';
        if (file_exists(public_path($file))) {
            return ["url" => Url::getHttpHost() . $file];
        }
        $result = QrCodeController::makeLeaseGoodsOrderCode($order_id, $file);
        if ($result) {
            return ["url" => Url::getHttpHost() . $result];
        }
        return false;
    }

    /**
     * @param $filter
     * 通过二维码
     */
    public static function getOrderInfoByQrCode($filter)
    {
        $order_id = Crypt::decrypt($filter['code_num']);
        $order = Order::where(['id' => $order_id])->with(['order_goods'])->first();
        if (empty($order)) {
            return false;
        }
        $orders = $order->toArray();
        $goods = (new LeaseGoods())->where(['id' => $orders['order_goods']['goods_id']])->first();
        $orders['goods_info'] = null;
        if ($goods) {
            $orders['goods_info'] = $goods->toArray();
        }
        if (isset($orders['goods_info']['goods_image'])) {
            $orders['goods_info']['goods_image'] = Url::getHttpHost() . 'upload/' . $orders['goods_info']['goods_image'];
        }
        if (isset($orders['order_goods']['goods_img'])) {
            $orders['order_goods']['goods_img'] = Url::getHttpHost() . 'upload/' . $orders['order_goods']['goods_img'];
        }
        return $orders;
    }


    /**
     * @param $filter
     * @return bool
     * 通过订单号获取订单详情
     */
    public static function getOrderInfoByOrderNum($filter)
    {
        $order_id = $filter['order_id'];
        $order = Order::where(['id' => $order_id])->with(['order_goods'])->first();
        if (empty($order)) {
            return false;
        }
        $orders = $order->toArray();
        $goods = (new LeaseGoods())->where(['id' => $orders['order_goods']['goods_id']])->first();
        $orders['goods_info'] = null;
        if ($goods) {
            $orders['goods_info'] = $goods->toArray();
        }
        if (isset($orders['goods_info']['goods_image'])) {
            $orders['goods_info']['goods_image'] = Url::getHttpHost() . 'upload/' . $orders['goods_info']['goods_image'];
        }
        if (isset($orders['order_goods']['goods_img'])) {
            $orders['order_goods']['goods_img'] = Url::getHttpHost() . 'upload/' . $orders['order_goods']['goods_img'];
        }
        return $orders;
    }






    /**
     * @param $data
     * 确认领取物品(医护端扫码确认
     */
    public static function confirmPickUp($data)
    {
        //订单详情
        $order = Order::getOrderDetail($data['order_id']);
        if ($order->pay_status != 1) {
            return "该订单没有支付,不能操作取货步骤!";
        }
        if ($order->delivery_status == 1) {
            return "该订单已被取货,不能重复操作!";
        }
        if($order->work_id != $data['work_id']){
            return "该订单不属于该工作室,您无权操作!";
        }
        $doc = (new Doctor())->where(['work_id'=>$data['work_id'],'id'=>$data['doctor_id']])->first();
        if(!$doc){
            return "该订单不属于您的工作室订单,您无权操作!";
        }
        $order->delivery_status = 1;
        $order->delivery_time = date("Y-m-d H:i:s",time());
        return  $order->save();
    }


    /***
     * @param $data
     * 获取下单人手机号
     */
    public static function getOrderUserMobile($data)
    {
        //订单详情
        $order = Order::getOrderDetail($data['order_id']);
        return User::where(['id' => $order->user_id])->select("phone")->first()->toArray();
    }

    /**
     * @param $data
     * 退还押金
     */
    public static function setReturnBackUserMoney($data)
    {
        $order = Order::getOrderDetail($data['order_id']);
        if ($order->pay_status != 1) {
            return "该订单没有支付,不能操作退还步骤!";
        }
        if ($order->order_status != 0) {
            return "该订单状态下,不能操作退还步骤!";
        }
        if ($order->delivery_status == 0) {
            return "该订单还没有取货,不能操作退还押金操作!";
        }
        if ($order->work_id != $data['work_id']) {
            return "该订单不属于该工作室,您无权操作!";
        }
        $doc = (new Doctor())->where(['work_id' => $data['work_id'], 'id' => $data['doctor_id']])->first();
        if (!$doc) {
            return "该订单不属于您的工作室订单,您无权操作!";
        }
        if ($data['type'] == 1) { //需要扣除押金
            if($data['money'] >= $order->pay_price){
                return "如果您要扣除全部押金，请点击患者买断按钮!";
            }
            $order_goods = OrderGoods::where(['order_id'=>$data['order_id']])->first();
            $order_goods->is_deduct = $data['type'];
            $order_goods->deduct_money = $data['money'];
            $order_goods->deduct_reason = $data['reason'];
            $order_goods->save();
            if ($order->pay_type == 1) { //微信
                $lit['sn'] = $order->sn;
                $lit['price'] = $order->pay_price;
                $lit['refund_price'] = $order->pay_price - $data['money'];
                $lit['return_sn'] = (new Order())->orderNumber();
                $wxs = (new WxPayController())->depositReturn($lit);//退一部分钱
                if ($wxs == 'refund') {
                    $dtl = self::setOrderStatusByAliPay($order);
                    if ($dtl) {
                        return true;
                    }
                }
                return true;
            } elseif ($order->pay_type == 2) { //支付宝
                $lit['sn'] = $order->sn;
                $lit['money'] = $order->pay_price - $data['money'];
                $lit['back_sn'] = (new Order())->orderNumber();
                $istrue = (new PaymentController())->doReturn($lit);
                if ($istrue) {
                    //退回账单
                    $dtl = self::setOrderStatusByAliPay($order);
                    if ($dtl) {
                        return true;
                    }
                }
            }
        } else { //原路返回
            if ($order->pay_type == 1) { //微信
                $lit['sn'] = $order->sn;
                $lit['price'] = $order->pay_price;
                $lit['return_sn'] = (new Order())->orderNumber();
                $wxs = (new WxPayController())->returnBack($lit);
                if ($wxs == 'refund') {
                    $dtl = self::setOrderStatusByAliPay($order);
                    if ($dtl) {
                        return true;
                    }
                }
                return true;
            } elseif ($order->pay_type == 2) { //支付宝
                $lit['sn'] = $order->sn;
                $lit['money'] = $order->pay_price;
                $lit['back_sn'] = (new Order())->orderNumber();
                $istrue = (new PaymentController())->doReturn($lit);
                if ($istrue) {
                    //退回账单
                    $dtl = self::setOrderStatusByAliPay($order);
                    if ($dtl) {
                        return true;
                    }
                }
            }
        }
    }

    /**
     * @param $order设置支付宝订单状态
     */
    public static function setOrderStatusByAliPay($order)
    {
        (new FinancialStatementsLog())->setReturnBackUserMoneyOrderBack($order);
        //取消订单
        $lit = ['order_status' => 1,
            'receive_status' => 1,
            'receive_time' => date("Y-m-d H:i:s", time()),
            'evaluate_status' => 1,
            'evaluate_time' => date("Y-m-d H:i:s", time())
        ];
       $state = Order::where([['id', '=', $order->id]])->update($lit);
       if($state){
           return true;
       }
    }

    /***
     * @param $param
     * 患者买断处理
     */
    public static function setPatientBuyComplete($data)
    {
        $order = Order::getOrderDetail($data['order_id']);
        if ($order->pay_status != 1) {
            return "该订单没有支付,不能操作退还步骤!";
        }
        if ($order->order_status != 0) {
            return "该订单状态下,不能操作退还步骤!";
        }
        if ($order->delivery_status == 0) {
            return "该订单还没有取货,不能操作退还押金操作!";
        }
        if ($order->work_id != $data['work_id']) {
            return "该订单不属于该工作室,您无权操作!";
        }
        $doc = (new Doctor())->where(['work_id' => $data['work_id'], 'id' => $data['doctor_id']])->first();
        if (!$doc) {
            return "该订单不属于您的工作室订单,您无权操作!";
        }
        $order_goods = new  OrderGoods();
        $order_goods->where(["order_id"=>$order->id])->update(['return_type'=>1]);
        (new FinancialStatementsLog())->setPatientBuyCompleteBill($order);
        //订单已完成
        $lit = ['order_status' => 1,
            'receive_status' => 1,
            'receive_time' => date("Y-m-d H:i:s", time()),
            'evaluate_status' => 1,
            'evaluate_time' => date("Y-m-d H:i:s", time())
        ];
        $state = Order::where([['id', '=', $order->id]])->update($lit);
        if($state){
            return true;
        }

    }


    /**
     * @param $data
     * 获取待使用红点数
     */
    public static function getUsingNum($data)
    {
        return Order::where([['work_id', '=', $data['work_id']], ['order_type', '=', 5], ['pay_status', '=', 1], ['delivery_status', '=', 0], ['order_status', '=', 0]])->count("id");
    }
}
